import { InputProps, Input } from "antd";
import { useState, useEffect } from "react";

export interface IPhoneInputProps extends Omit<InputProps, 'onChange'> {
  value?: string;
  onChange?: (value: string) => void;
}

export function PhoneInput(props: IPhoneInputProps) {
  const { value, onChange, ..._p } = props;

  const [_value, _set_value] = useState(value?.replace(/\D/g, '').replace(/0*(\d+)/, '$1'))

  useEffect(() => {
    _set_value(value?.replace(/\D/g, '').replace(/0*(\d+)/, '$1'))
  }, [value])

  const handle_change = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { value: inputValue } = e.target;
    if (/^-?\d*(\.\d*)?$/.test(inputValue) || inputValue === '' || inputValue === '-')
      onChange?.(inputValue);
  };

  const handle_blur = () => {
    let temp = value;
    if (value?.charAt(value.length - 1) === '.' || value === '-')
      temp = value.slice(0, -1);
    onChange?.(temp?.replace(/0*(\d+)/, '$1') ?? '');
  };

  return <>
    <Input
      value={_value}
      onChange={handle_change}
      onBlur={handle_blur}
      placeholder="手机号"
      maxLength={11}
      {..._p}
    />
  </>;
}